import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import '../../services/ml/tflite_service.dart';
import '../pose/pose_painter.dart';

/// 相机预览组件
/// 显示相机预览和姿态检测结果
/// 创建时间：2024-01-23

class CameraPreviewWidget extends StatefulWidget {
  final CameraController? cameraController;

  const CameraPreviewWidget({super.key, this.cameraController});

  @override
  CameraPreviewWidgetState createState() => CameraPreviewWidgetState();
}

class CameraPreviewWidgetState extends State<CameraPreviewWidget>
    with WidgetsBindingObserver {
  final TFLiteService _tfliteService = TFLiteService();
  final _logger = Logger('CameraPreviewWidget');
  List<Offset> points = [];
  List<dynamic> poses = [];
  Size? imageSize;
  bool _isProcessing = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initializeCamera();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _stopCamera();
    super.dispose();
  }

  void _stopCamera() {
    widget.cameraController?.stopImageStream();
    _tfliteService.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (widget.cameraController == null ||
        !widget.cameraController!.value.isInitialized) {
      return;
    }

    if (state == AppLifecycleState.inactive) {
      _stopCamera();
    } else if (state == AppLifecycleState.resumed) {
      _initializeCamera();
    }
  }

  void _initializeCamera() async {
    await widget.cameraController?.initialize();
    if (!mounted) return;

    setState(() {
      imageSize = Size(
        widget.cameraController!.value.previewSize!.height,
        widget.cameraController!.value.previewSize!.width,
      );
    });

    await _tfliteService.loadModel();
    widget.cameraController?.startImageStream(detectPose);
  }

  void detectPose(CameraImage image) async {
    if (!mounted || _isProcessing) return;

    try {
      _isProcessing = true;
      var results = await _tfliteService.runPoseEstimation(image);
      if (results != null && mounted) {
        setState(() {
          points = getPointsFromResults(results);
        });
      }
    } catch (e, stackTrace) {
      _logger.severe('姿态检测错误', e, stackTrace);
    } finally {
      _isProcessing = false;
    }
  }

  List<Offset> getPointsFromResults(dynamic results) {
    if (results == null) return [];

    List<Offset> newPoints = [];
    try {
      for (var result in results) {
        _logger.info('关键点数据: $result');

        if (result == null ||
            !result.containsKey('x') ||
            !result.containsKey('y')) {
          continue;
        }

        var xValue = result['x'];
        var yValue = result['y'];

        double x = 0.0;
        double y = 0.0;

        if (xValue is int) {
          x = xValue.toDouble();
        } else if (xValue is double) {
          x = xValue;
        } else {
          _logger.warning('无效的x坐标类型: ${xValue.runtimeType}');
          continue;
        }

        if (yValue is int) {
          y = yValue.toDouble();
        } else if (yValue is double) {
          y = yValue;
        } else {
          _logger.warning('无效的y坐标类型: ${yValue.runtimeType}');
          continue;
        }

        newPoints.add(Offset(x, y));
      }
    } catch (e, stackTrace) {
      _logger.severe('解析关键点数据失败', e, stackTrace);
    }
    return newPoints;
  }

  @override
  Widget build(BuildContext context) {
    if (widget.cameraController == null ||
        !widget.cameraController!.value.isInitialized) {
      return const Center(child: CircularProgressIndicator());
    }

    return Stack(
      children: <Widget>[
        Positioned.fill(
          child: AspectRatio(
            aspectRatio: widget.cameraController!.value.aspectRatio,
            child: CameraPreview(widget.cameraController!),
          ),
        ),
        Positioned.fill(
          child: CustomPaint(
            painter: PosePainter(poses, points, imageSize ?? Size.zero),
          ),
        ),
      ],
    );
  }
}
